package com.direction.hold.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.cheln.explorer.actions.sort.DBSort;
import cn.cheln.explorer.actions.sort.Sort;
import cn.cheln.explorer.beans.FileInfo;
import cn.cheln.explorer.beans.FileUtil;
import cn.cheln.explorer.beans.MusicInfo;
import cn.cheln.explorer.config.Config;
import cn.cheln.explorer.config.Constants;
import cn.cheln.explorer.ds.database.Category;
import cn.cheln.explorer.ds.database.CategoryInfo;
import cn.cheln.explorer.ds.database.MimeSrc;
import cn.cheln.explorer.ds.database.copersynch.DatasrcDelete;
import cn.cheln.explorer.ds.scan.ScanService;
import cn.cheln.explorer.ds.scan.ScanUpdateReceiver;
import cn.cheln.explorer.ds.uri.AccountNode;
import cn.cheln.explorer.ds.uri.NavigationConstants;
import cn.cheln.explorer.ds.uri.NavigationNode;
import cn.cheln.explorer.func.setup.PackageInstallManager;
import cn.cheln.explorer.ui.SearchListViewHolder;
import cn.cheln.explorer.ui.Switcher;
import cn.cheln.explorer.ui.ViewHolder;
import cn.cheln.explorer.util.Commit;
import cn.cheln.explorer.util.MusicBroadcastReceiver;
import cn.cheln.explorer.util.PackageReceiver;
import cn.cheln.explorer.util.ReadSystemMemory;
import cn.cheln.support.data.text.xml.SPUtil;
import cn.cheln.support.log.Logs;
import cn.cheln.support.mobile.sdcard.SDcardChecker;
import cn.cheln.support.ui.DensityUtil;
import cn.cheln.support.ui.adapter.MapAdapter;
import cn.power.shine.R;

public class CountActivity extends FileCursorActivity {

    public static final int MESS_UPDATE_UI_COUNT = 2;
    protected static final int MESS_LOAD_FINISH = 0;
    protected static final int MESS_SCAN_FINISH = 1;
    public static CountActivity categoryActivity;
    public ProgressDialog pd;
    public int countSharedPrefernce = 0;
    public ViewHolder homeViewHolder;
    public boolean finishStarted;
    public boolean finished;
    protected TextView totalNumView;
    protected AdapterView categoryAdaptView;
    protected View homeView;
    protected Category categoryItem;
    protected boolean bcurrentpage;
    protected TextView plusNumView;
    protected Boolean launchFlag;
    protected View progressbar_updown;
    protected Bundle savedInstanceState;
    protected MapAdapter homeAdapter;
    List<CategoryInfo> category = new ArrayList<CategoryInfo>(0);
    boolean startupFlag = false;
    SharedPreferences sp;
    boolean isNoZero = false;
    ScanUpdateReceiver scanUpdateReceiver;
    PackageReceiver packageReceiver;
    boolean categoryVisitFlag;
    Handler createHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ((HomeViewHolder) getViewHolderInstance())
                            .notifyCountData(true);
                    break;
                case 1:
//                    if (Config.versioncode < 12) {
                        Commit.showDialog(CountActivity.this,
                                Constants.SharedPrefernce.KEY_USEDCOUNT,
                                Constants.OperationContants.InviteCommit,
                                Config.CommitCount);
//                    }
                    break;
                case 2:
                    if (Config.versioncode >= 12&&Config.versioncode <= 13) {
                        Boolean bl = ((Boolean) SPUtil.getValue(
                                context, Constants.SharedPrefernce.File,
                                "tellaskexistornot", Boolean.class));
                        if (bl == null || !bl) {
                            SPUtil.putValue(context,
                                    Constants.SharedPrefernce.File,
                                    "tellaskexistornot", true);
                            context.showDialog(Constants.OperationContants.askForIFPreserve);
                        }
                    }
                    break;
            }
        }

    };
    boolean atTopToSearch = true;
    private View viewAudio;
    private View viewImage;
    private View viewVideo;
    private View viewDoc;
    private View viewApk;
    private View viewTheme;
    private Map blockSizeMap;
    private boolean scanBarToHideFlag = false;
    private MusicBroadcastReceiver mbr;

    public void initDBData(String certainCategory) {
        category.clear();
        Map<String, Category> wholeCategories = MimeSrc.initWholeCategories(
                context, certainCategory, category);
    }

    @Override
    protected void updateCountActivity(FileInfo fileInfo) {
        DatasrcDelete.recursiveUpdateDel(fileInfo, this);
        refresh();
    }

    @Override
    public ViewHolder getViewHolder() {
        // TODO Auto-generated method stub
        return getViewHolder(CountActivity.class.getName());
    }
//	public LWTReceiver lwtReceiver;

    @Override
    protected void setHiddenFileShowFlag() {
        isHiddenFileShow = Config.ACCOUNT_HIDE_OPTION;
    }

    @Override
    public void setSort() {
        policy = new DBSort(Sort.SORT_POLICY_TITLE, Sort.SORT_SEQ_ASC);
    }

    @Override
    public boolean isInListDetail() {
        return !navTool.isAtTop();
    }

    public List<CategoryInfo> initCount() {
        if (category.isEmpty()) {
            isNoZero = addEmptyCategory(R.string.music, R.drawable.lewa_ic_folder_music_mp3,
                    category) == 0;
            isNoZero = addEmptyCategory(R.string.image, R.drawable.lewa_ic_loading_picture,
                    category) == 0;
            isNoZero = addEmptyCategory(R.string.video, R.drawable.lewa_ic_folder_video,
                    category) == 0;
            isNoZero = addEmptyCategory(R.string.doc, R.drawable.doc, category) == 0;
            isNoZero = addEmptyCategory(R.string.app, R.drawable.apk, category) == 0;
        }
        return category;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        // TODO Auto-generated method stub
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return super.onMenuItemClick(item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void swithToPrivacyActivity() {
        // EqualCheck nc = new EqualCheck(ObjectSort.SORT_POLICY_TITLE,
        // ObjectSort.SORT_SEQ_ASC);
        // Collections.sort(OperationUtil.selectedEntities, nc);
        // if (nc.isResult()) {
        // Toast.makeText(context, R.string.same_name_files_operation_cancel,
        // Toast.LENGTH_LONG).show();
        // operationUtil.dataClear();
        // return;
        // }
        // SlideActivity.paramActivity.isInOperation =
        // OperationUtil.OPER_TYPE_MOVE_PRIVACY;
        // showBottomBar(View.GONE);
        // SlideActivity.fileActivityInstance.setDisplayScreen(2);
        // ((PrivacyActivity) PrivacyActivity.activityInstance).switchToMove();
    }

    @Override
    protected void cutOrCopy(int command) {
        if (performCountActivityCopy(command)) {
            return;
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logs.i("======== categoryVisitFlag " + categoryVisitFlag);
        if (categoryVisitFlag) {
            String value_lwt_deleted = (String) SPUtil.getValue(
                    context, Constants.SharedPrefernce.RememberedCategory,
                    Constants.SharedPrefernce.KEY_LWT_ISDELETED, String.class);
            if (value_lwt_deleted != null
                    && !value_lwt_deleted.trim().equals("")) {
                File deletedLWT = new File(value_lwt_deleted);
                if (!deletedLWT.exists()) {
                    DatasrcDelete.recursiveUpdateDel(new FileInfo(deletedLWT,
                            context), context);
                    viewHolder.refresh();
                }
                SPUtil.putValue(context,
                        Constants.SharedPrefernce.RememberedCategory,
                        Constants.SharedPrefernce.KEY_LWT_ISDELETED, "");
            }
            Logs.i("======== categoryVisitFlag after " + categoryVisitFlag);
        } else {
            categoryVisitFlag = true;
        }
    }

    @Override
    public View getPageView() {
        // TODO Auto-generated method stub
        return this.homeView;
    }

    @Override
    public void setPageView(View list) {
        // TODO Auto-generated method stub
        this.homeView = list;
    }

    public void callSuperStartup() {
        super.startup();
        ((SearchListViewHolder) this.getViewHolder(SearchActivity.class
                .getName())).init();
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.context = this;
        categoryVisitFlag = false;

        categoryActivity = this;
        String action = this.getIntent().getAction();
        loadCountViewHolder();
        // if (Config.is4_0Lower) {
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();
                if (scanUpdateReceiver == null) {

                    scanUpdateReceiver = new ScanUpdateReceiver(CountActivity.this);
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
                    filter.addAction(ScanUpdateReceiver.ACTION_RECEIVER_SCAN);
                    filter.addAction(ScanUpdateReceiver.ACTION_SCANNING);
                    CountActivity.this.registerReceiver(scanUpdateReceiver, filter);

                    // IntentFilter filterCancelApkNotify = new IntentFilter();
                    // apkNotifyBroadcast = new ApkNotifyBroadcast();
                    // filterCancelApkNotify
                    // .addAction(ApkNotifyBroadcast.ACTION_APK_NOTIFY_CANCEL);
                    // CountActivity.this.registerReceiver(apkNotifyBroadcast,
                    // filterCancelApkNotify);

                    mbr = new MusicBroadcastReceiver();
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction("com.shortcut.music.metachanged");
                    intentFilter.addAction("com.shortcut.music.queuechanged");
                    intentFilter.addAction("com.shortcut.music.playbackcomplete");
                    intentFilter.addAction("com.shortcut.music.playstatechanged");
                    CountActivity.this.registerReceiver(mbr, intentFilter);
                    // lwtReceiver = new LWTReceiver(CountActivity.this);
                    // IntentFilter lwtfilter = new IntentFilter();
                    // lwtfilter
                    // .addAction(Constants.GoToInvokeLWT.ACTION_DELETE_LWT);
                    // CountActivity.this.registerReceiver(lwtReceiver,
                    // lwtfilter);
                }
                try {
                    Thread.sleep(1900);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (packageReceiver == null) {
                    packageReceiver = new PackageReceiver(CountActivity.this);
                    IntentFilter pfilter = new IntentFilter();
                    pfilter.addAction(Intent.ACTION_PACKAGE_ADDED);
                    pfilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
                    pfilter.addDataScheme("package");
                    CountActivity.this.registerReceiver(packageReceiver,
                            pfilter);
                    SDcardChecker.broadcastRec = new SDcardChecker.MediaScannerBroadcast();
                    SDcardChecker.registerSDcardIntentListener(
                            CountActivity.this, SDcardChecker.broadcastRec);
                }
                startService(new Intent(CountActivity.this, ScanService.class));

            }

        }.start();
        // }
    }

    public void setScanBarHide(boolean scanBarToHideFlag) {
        this.scanBarToHideFlag = scanBarToHideFlag;
    }

    public void hideScanBar(int makeHide) {
        View scanBar = findViewById(R.id.scanProgress);
        if (scanBar != null) {
            scanBar.setVisibility(makeHide);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        if (this.navTool.isAtTop()) {
            return false;
        }
        menu.clear();
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sdcardmenu, menu);
        menu.removeItem(R.id.menu_new_dir);
        setMenuItemById(menu.findItem(R.id.menu_sort).getSubMenu(), menu
                .findItem(R.id.menu_sort).getSubMenu().size());
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        if (this.navTool.getCurrNavEntitySource() != null
                && this.navTool.getCurrNavEntitySource().toString()
                .toLowerCase()
                .equals(Constants.CateContants.CATE_IMAGES)) {
            if (menu.findItem(MENU_MY_PIC_SIZE) == null) {
                menu.add(0, MENU_MY_PIC_SIZE, 0,
                        getString(R.string.menu_my_pic_size)).setIcon(
                        R.drawable.ic_menu_pic);
            }
        } else {
            if (this.navTool.getCurrNavEntitySource() != null
                    && this.navTool.getCurrNavEntitySource().toString()
                    .toLowerCase()
                    .equals(Constants.CateContants.CATE_MUSIC)) {
                setMenuItemById(menu.findItem(R.id.menu_sort).getSubMenu(),
                        menu.findItem(R.id.menu_sort).getSubMenu().size());
            }
            menu.removeItem(MENU_MY_PIC_SIZE);
        }

        Menu m = menu.findItem(R.id.menu_sort).getSubMenu();
        if (this.navTool.navEntity.peek().producingSource.toString()
                .toUpperCase().equals("AUDIO")) {
            // if (Config.isLewaRom) {
            // hideMusicMenu(m, true);
            // }
        } else {
            if (sortMenuMarkInit == SortMenuInAPK
                    || sortMenuMarkInit == SortMenuInMusic) {
                menu.findItem(R.id.menu_sort).getSubMenu()
                        .findItem(R.id.menu_cateogry_sort_name)
                        .setChecked(true);
            }
            MenuItem sortType = menu.findItem(R.id.menu_sort).getSubMenu()
                    .findItem(R.id.menu_cateogry_sort_type);
            sortType.setVisible(!this.navTool.navEntity.peek().producingSource
                    .equals(Constants.CateContants.CATE_PACKAGE));
            hideMusicMenu(m, false);
        }
        return true;
    }

    public ViewHolder getViewHolderInstance() {
        if (homeViewHolder == null) {
            // homeViewHolder = new HomeViewHolder(homeView, this);
            homeViewHolder = getViewHolder(CountActivity.class.getName());
        }
        return homeViewHolder;
    }

    public ViewHolder loadCountViewHolder() {
        return loadViewHolder(CountActivity.class.getName(),
                new HomeViewHolder(homeView, this));
    }

    @Override
    public void enterDir(FileInfo fileInfo) {
        // TODO Auto-generated method stub

        super.enterDir(fileInfo);
    }

    public void searchAgain(FileInfo fileInfo) {

    }

    @Override
    public void startup() {

        // TODO Auto-generated method stub
        if (pd != null && !pd.isShowing()) {
            pd.show();
        }

        new Thread() {

            @Override
            public void run() {
                super.run();

                navTool.push(new AccountNode("",
                        NavigationConstants.CATEGORYHOME));
                blockSizeMap = FileUtil
                        .getAvailableStore(NavigationConstants.SDCARD_PATH);
                MusicInfo.init(context);
                Float image_filter_size = Config.image_filter_size = (Float) SPUtil
                        .getValue(
                                context,
                                Constants.SharedPrefernce.SP_IMAGE_FILTER_SIZE,
                                Constants.SharedPrefernce.KEY_IMAGE_FILTER_SIZE,
                                Float.class);
                if (image_filter_size == null || image_filter_size == -1) {
                    SPUtil.putValue(context,
                            Constants.SharedPrefernce.SP_IMAGE_FILTER_SIZE,
                            Constants.SharedPrefernce.KEY_IMAGE_FILTER_SIZE,
                            -1F);
                    Config.image_filter_size = -1F;
                }
            }
        }.start();
        showCreateHandler();

//        this.searchPageView = contentView;
        // ((HomeViewHolder) getViewHolderInstance())
        // .notifyCountData(true);
    }

    public void showCreateHandler() {
        new Thread() {

            @Override
            public void run() {
                super.run();
                countData();

                Commit.ifShowCommitInvite(CountActivity.this,
                        Constants.SharedPrefernce.KEY_USEDCOUNT,
                        Config.CommitCount);
                createHandler.sendEmptyMessage(0);
                createHandler.sendEmptyMessage(1);
                createHandler.sendEmptyMessage(2);
            }
        }.start();
        Switcher.viewFlowTo(getViewHolder(CountActivity.class.getName()),
                contentView, this);
    }

    public void baseSwitchSearchMain(boolean to) {
        atTopToSearch = !to;
        if (to) {
            LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            ((LinearLayout) (findViewById(R.id.searchlayout)))
                    .setLayoutParams(ll);
            findViewById(R.id.listmain).setVisibility(View.VISIBLE);
            // findViewById(R.id.grid).setVisibility(View.GONE);
            // findViewById(R.id.usage).setVisibility(View.GONE);
        } else {
            findViewById(R.id.listmain).setVisibility(View.GONE);
            // findViewById(R.id.grid).setVisibility(View.VISIBLE);
            // findViewById(R.id.usage).setVisibility(View.VISIBLE);
            // LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
            // LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            // ((LinearLayout) (findViewById(R.id.searchlayout)))
            // .setLayoutParams(ll);
            this.getWindow().getDecorView().invalidate();
//            setEmptychanged(true);
        }
    }

    @Override
    protected String getEmptyText() {
        return this.getString(R.string.nofile,
                this.getString(R.string.position_category));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (this.navTool.isAtTop()) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    protected int addEmptyCategory(int nameRes, int DrawableRes,
                                   List<CategoryInfo> category) {
        // if (sp == null) {
        // sp = this.getPreferences(countSharedPrefernce);
        // }
        // int count = sp.getInt(this.getString(nameRes), 0);
        int count = 0;
        Category categoryItem = MimeSrc.getEmptyCategory(this,
                this.getString(nameRes),
                this.getResources().getDrawable(DrawableRes));
        categoryItem.categoryInfo.count = "" + count;
        category.add(categoryItem.categoryInfo);
        return count;
    }

    @Override
    public void access(NavigationNode navigation, int newPos,
                       boolean notifyDataSetChanged, int mode, int status, int accessFlag) {
        access(navigation, newPos, notifyDataSetChanged, mode, status);
    }

    @Override
    public void access(NavigationNode navigation, int newPos,
                       boolean notifyDataSetChanged, int mode, int status) {
    }

    @Override
    public void handlerRead(Object previousSource, boolean startRoot) {
    }

    @Override
    protected void setNavigationPosAndNode(int newPos, int mode,
                                           NavigationNode navSource) {
        if (mode == MODE_NEW) {
            if (this.navTool.navEntity.size() != 0) {
                listview.setSelection(newPos);
            }
        }
    }

    @Override
    protected boolean backward() {
        if (!this.navTool.isAtTop() || !atTopToSearch) {
            showBottomBar(View.GONE);
            if (!atTopToSearch) {
//                this.searchHolder.finish();
//
//                Switcher.viewFlowTo(this.loadCountViewHolder(), contentView,
//                        this);
//                getSearchBox().setText("");
//                getSearchBox().removeTextChangedListener(searchViewTextWatcher);
//                // must add after "getSearchBox().setText("");"
//                emptychanged = true;
            } else {
                this.navTool.pop();
                showCreateHandler();
            }
            return true;
        }
        return false;
    }

    public void switchApkBar(boolean switchon) {
        if (this.bottomToolbar != null) {
            if (switchon) {
                this.bottomToolbar.findViewById(R.id.toolbar_cancel)
                        .setVisibility(View.GONE);
                this.bottomToolbar.findViewById(R.id.toolbar_cancel_v_line)
                        .setVisibility(View.GONE);
                this.bottomToolbar.findViewById(R.id.operate).setVisibility(
                        View.VISIBLE);
                this.bottomToolbar.findViewById(R.id.apkpre_v_line)
                        .setVisibility(View.VISIBLE);
            } else {
                this.bottomToolbar.findViewById(R.id.toolbar_cancel)
                        .setVisibility(View.VISIBLE);
                this.bottomToolbar.findViewById(R.id.toolbar_cancel_v_line)
                        .setVisibility(View.VISIBLE);
                this.bottomToolbar.findViewById(R.id.operate).setVisibility(
                        View.GONE);
                this.bottomToolbar.findViewById(R.id.apkpre_v_line)
                        .setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void showBottomBar(int visibility) {
        if (this.navTool.getCurrNavEntitySource() != null
                && this.navTool.getCurrNavEntitySource().toString()
                .toLowerCase()
                .equals(Constants.CateContants.CATE_PACKAGE)) {
            boolean switchOptn = false;
            if (visibility == View.VISIBLE) {
                switchOptn = true;
            } else if (visibility == View.GONE) {
                switchOptn = false;
            }
            switchApkBar(switchOptn);
//            switchApkBar(false);
        } else {
            switchApkBar(false);
        }
        super.showBottomBar(visibility);
    }

    @Override
    protected void showApkViewContextMenux(ContextMenu menu,
                                           ContextMenuInfo menuInfo) {
        menu.setHeaderTitle(R.string.operate);
        menu.add(0, MENU_INSTALL, 0, R.string.batch_install)
                .setCheckable(false).setChecked(false)
                .setOnMenuItemClickListener(new OnMenuItemClickListener() {

                    public boolean onMenuItemClick(MenuItem arg0) {
                        if (PackageInstallManager.isInInstall) {
                            Toast.makeText(context,
                                    R.string.prohibetRepeatingExectuing,
                                    Toast.LENGTH_LONG).show();
                            showBottomBar(View.GONE);
                            return true;
                        }
                        showDialog(DIALOG_PREFER_INSTALL);
                        return false;
                    }
                });
        menu.add(0, MENU_MORE_SEND, 0, R.string.share).setCheckable(false)
                .setChecked(false)
                .setOnMenuItemClickListener(new OnMenuItemClickListener() {

                    public boolean onMenuItemClick(MenuItem arg0) {
                        send();
                        return false;
                    }
                });

    }

    @Override
    public String getNavBarWholeShowText() {
        String text = "";
        NavigationNode node;
        for (int i = 0; i < this.navTool.navEntity.size(); i++) {
            if ((node = this.navTool.navEntity.get(i)) == null) {
                continue;
            }
            text += " / " + node.displayname;
        }
        text = text.substring(3);
        return text;
    }

    @Override
    protected boolean navigate(MenuItem item) {
        // TODO Auto-generated method stub
        Logs.i("", "---" + item.getTitle());
        int theId = item.getItemId() - MENU_PATH_OFFSET;
        if (theId < this.navTool.navEntity.size()) {
            if (theId == 0) {
                this.backward();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (this.pd != null) {
            this.pd.dismiss();
        }
        pd = null;
        if (scanUpdateReceiver != null) {
            CountActivity.this.unregisterReceiver(scanUpdateReceiver);
            CountActivity.this.unregisterReceiver(packageReceiver);
            // CountActivity.this.unregisterReceiver(apkNotifyBroadcast);
//			CountActivity.this.unregisterReceiver(lwtReceiver);
            SDcardChecker.unregisterSDcardIntentListener(CountActivity.this,
                    SDcardChecker.broadcastRec);
//            CountActivity.this.unregisterReceiver(mbr);
        }
        super.onDestroy();
    }

    public void refresh(boolean callScanner) {
        if (!callScanner) {
            refresh();
            return;
        }
        // scan flagss
        if (Config.isLewaRom
                || Category
                .intCat(this.navTool.navEntity.peek().producingSource
                        .toString().toLowerCase()) != -1) {
            mediaScannerRefresh();
            return;
        }
        Intent intent = new Intent(this, ScanService.class);
        intent.putExtra(ScanUpdateReceiver.SCAN_TYPE,
                this.navTool.navEntity.peek().producingSource.toString());
        this.startService(intent);
    }

    private void mediaScannerRefresh() {
        if (SDcardChecker.MediaScannerBroadcast.scanCat != null) {
            Toast.makeText(
                    context,
                    context.getString(R.string.scaning,
                            SDcardChecker.MediaScannerBroadcast.scanCat),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        CountActivity.categoryActivity.setScanBarHide(false);
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
                .parse("file://" + Environment.getExternalStorageDirectory())));
        SDcardChecker.mediaScanning = true;
        if (CountActivity.categoryActivity.navTool.navEntity.size() != 0) {
            SDcardChecker.MediaScannerBroadcast.scanCat = CountActivity.categoryActivity.navTool.navEntity
                    .peek().displayname;
            Toast.makeText(
                    context,
                    context.getString(R.string.scaning_toast,
                            SDcardChecker.MediaScannerBroadcast.scanCat),
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void refresh() {
        if (SDcardChecker.srcardStateResolve(true, this)) {
            return;
        }
        if (!atTopToSearch) {
            return;
        }
        if (this.navTool.isAtTop()) {
            showCreateHandler();
            return;
        }
        loadFileCursor().refresh();
        reFreshCheckboxVisible();
    }

    public void recovery() {

        if (this.navTool.navEntity.isEmpty() || this.navTool.isAtTop()) {
            this.startup();
            return;
        }
        this.gotoCat();
        reFreshCheckboxVisible();
    }

    @Override
    protected void prepareMusicInfo(int visible, FileInfo info) {
        super.prepareMusicInfo(visible, info);
        // if (this.navTool.navEntity.peek().producingSource.toString()
        // .toUpperCase().equals("AUDIO")) {
        // MusicInfo mi = (MusicInfo) info;
        // value_artist.setText(mi.artist);
        // value_album.setText(mi.album.replace("-", "").trim());
        // }
    }

    @Override
    public void sort() {
        refresh();

    }

    @Override
    public String prepareMime() {
        String mimePrefix = this.navTool.navEntity.peek().producingSource
                .toString();
        if (mimePrefix.equals(Constants.CateContants.CATE_DOCS)
                || mimePrefix.equals(Constants.CateContants.CATE_PACKAGE)
                || mimePrefix.equals(Constants.CateContants.CATE_MUSIC)) {
            return "*/*";
        } else {
            return mimePrefix + "/*";
        }
    }

    @Override
    public int[] getMenuIds() {
        int[] result = null;
        if (!this.navTool.isAtTop()) {
            result = new int[]{R.id.menu_cateogry_sort_name,
                    R.id.menu_cateogry_sort_time, R.id.menu_cateogry_sort_size,
                    R.id.menu_cateogry_sort_type};
        }
        return result;
    }

    public void countData() {
        if (MimeSrc.categoryRepository == null
                || MimeSrc.categoryRepository.isEmpty()) {
            initCount();
            initDBData(null);
        }
        MimeSrc.recountCategoryNum(CountActivity.this);
    }

    public class HomeViewHolder extends ViewHolder {
        boolean inited;

        public HomeViewHolder(View view, CommonActivity activity) {
            super(view, activity);
        }

        @Override
        public void start() {
            if (view == null) {
                view = LayoutInflater.from(context).inflate(
                        R.layout.category_2_0, null);
                contentView = view;
            }
            activity.setContentView(view);
            initUI();

        }

        public void rebind() {
            uiStatusUpdate();
            notifyCountData(inited);
        }

        @Override
        public void init() {
            // TODO Auto-generated method stub
            inited = true;
        }

        private void initUI() {
            viewAudio = findViewById(R.id.audio);
            ((ImageView) (viewAudio.findViewById(R.id.categoryImage)))
                    .setImageResource(R.drawable.lewa_ic_folder_music_mp3);
            ((TextView) (viewAudio.findViewById(R.id.categoryTypeName)))
                    .setText(R.string.music);
            ((TextView) (viewAudio.findViewById(R.id.categoryTotalNum)))
                    .setText(FileUtil.addParentheses("  ?  "));
            ((TextView) (viewAudio.findViewById(R.id.categoryTotalSize)))
                    .setText("0 B");
            viewAudio.findViewById(R.id.itemLinearLayout).setOnClickListener(
                    categoryClickListener);
            viewImage = findViewById(R.id.image);
            ((ImageView) (viewImage.findViewById(R.id.categoryImage)))
                    .setImageResource(R.drawable.lewa_ic_loading_picture);
            ((TextView) (viewImage.findViewById(R.id.categoryTypeName)))
                    .setText(R.string.image);
            ((TextView) (viewImage.findViewById(R.id.categoryTotalNum)))
                    .setText(FileUtil.addParentheses("  ?  "));
            ((TextView) (viewImage.findViewById(R.id.categoryTotalSize)))
                    .setText("0 B");
            viewImage.findViewById(R.id.itemLinearLayout).setOnClickListener(
                    categoryClickListener);
            viewVideo = findViewById(R.id.video);
            ((ImageView) (viewVideo.findViewById(R.id.categoryImage)))
                    .setImageResource(R.drawable.lewa_ic_folder_video);
            ((TextView) (viewVideo.findViewById(R.id.categoryTypeName)))
                    .setText(R.string.video);
            ((TextView) (viewVideo.findViewById(R.id.categoryTotalNum)))
                    .setText(FileUtil.addParentheses("  ?  "));
            ((TextView) (viewVideo.findViewById(R.id.categoryTotalSize)))
                    .setText("0 B");
            viewVideo.findViewById(R.id.itemLinearLayout).setOnClickListener(
                    categoryClickListener);
            viewDoc = findViewById(R.id.doc);
            ((ImageView) (viewDoc.findViewById(R.id.categoryImage)))
                    .setImageResource(R.drawable.doc);
            ((TextView) (viewDoc.findViewById(R.id.categoryTypeName)))
                    .setText(R.string.doc);
            ((TextView) (viewDoc.findViewById(R.id.categoryTotalNum)))
                    .setText(FileUtil.addParentheses("  ?  "));
            ((TextView) (viewDoc.findViewById(R.id.categoryTotalSize)))
                    .setText("0 B");
            viewDoc.findViewById(R.id.itemLinearLayout).setOnClickListener(
                    categoryClickListener);
            viewApk = findViewById(R.id.apk);
            ((ImageView) (viewApk.findViewById(R.id.categoryImage)))
                    .setImageResource(R.drawable.apk);
            ((TextView) (viewApk.findViewById(R.id.categoryTypeName)))
                    .setText(R.string.app);
            ((TextView) (viewApk.findViewById(R.id.categoryTotalNum)))
                    .setText(FileUtil.addParentheses("  ?  "));
            ((TextView) (viewApk.findViewById(R.id.categoryTotalSize)))
                    .setText("0 B");
            viewApk.findViewById(R.id.itemLinearLayout).setOnClickListener(
                    categoryClickListener);
            if (Config.isLewaRom) {
                viewTheme = findViewById(R.id.theme);
                // ((ImageView) (viewTheme.findViewById(R.id.categoryImage)))
                // .setImageResource(R.drawable.theme);
                ((TextView) (viewTheme.findViewById(R.id.categoryTypeName)))
                        .setText(R.string.theme);
                ((TextView) (viewTheme.findViewById(R.id.categoryTotalNum)))
                        .setText(FileUtil.addParentheses("  ?  "));
                ((TextView) (viewTheme.findViewById(R.id.categoryTotalSize)))
                        .setText("0 B");
                viewTheme.findViewById(R.id.itemLinearLayout)
                        .setOnClickListener(categoryClickListener);
            }
            setSdcard(false);
            setMemory(false);
        }

        public void notifyCountData() {
            notifyCountData(true);
        }

        public void notifyCountData(Boolean loadData) {

            try {
                if (loadData) {
                    setSdcard(true);
                    setMemory(true);
                    bind_2_0(
                            findViewById(R.id.audio),
                            MimeSrc.categoryRepository
                                    .get(Constants.CateContants.CATE_MUSIC).categoryInfo);
                    bind_2_0(
                            viewImage.findViewById(R.id.image),
                            MimeSrc.categoryRepository
                                    .get(Constants.CateContants.CATE_IMAGES).categoryInfo);
                    bind_2_0(
                            findViewById(R.id.video),
                            MimeSrc.categoryRepository
                                    .get(Constants.CateContants.CATE_VIDEO).categoryInfo);
                    bind_2_0(
                            findViewById(R.id.doc),
                            MimeSrc.categoryRepository
                                    .get(Constants.CateContants.CATE_DOCS).categoryInfo);
                    bind_2_0(
                            findViewById(R.id.apk),
                            MimeSrc.categoryRepository
                                    .get(Constants.CateContants.CATE_PACKAGE).categoryInfo);
                    if (Config.isLewaRom) {
                        bind_2_0(
                                findViewById(R.id.theme),
                                MimeSrc.categoryRepository
                                        .get(Constants.CateContants.CATE_THEME).categoryInfo);
                    }

                    setSDProgress();
                    setMemProgress();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void bind_2_0(View view, CategoryInfo cateInfo) {
            Logs.i("----cateInfo" + cateInfo);
            ((TextView) view.findViewById(R.id.categoryTotalNum))
                    .setText(FileUtil.addParentheses(cateInfo.count));
            ((TextView) view.findViewById(R.id.categoryTotalSize))
                    .setText(cateInfo.size);
        }

        private void setSdcard(boolean load) {
            try {
                String availSize = "";
                String totalSize = "";
                if (load) {
                    HashMap<String, Object> blockSizeMap = FileUtil
                            .getAvailableStore(NavigationConstants.SDCARD_PATH);
                    availSize = blockSizeMap.get("availaBlocks").toString();
                    totalSize = blockSizeMap.get("totalBlocks").toString();
                }
                ((TextView) findViewById(R.id.sdcard_name_cnst))
                        .setText(getString(R.string.sdcardhome) + ":");
                ((TextView) findViewById(R.id.sdcard_capability))
                        .setText(load ? totalSize : " 0 B");
                ((TextView) findViewById(R.id.sdcard_avai_cnst))
                        .setText(getString(R.string.available) + ":");
                ((TextView) findViewById(R.id.sdcard_avai))
                        .setText(load ? availSize : " 0 B");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void setMemory(boolean load) {
            try {
                ((TextView) findViewById(R.id.memory_name_cnst))
                        .setText(getString(R.string.memory) + ":");
                ((TextView) findViewById(R.id.memory_capability))
                        .setText(load ? ReadSystemMemory.getTotalMemoryText()
                                : " 0 B");
                ((TextView) findViewById(R.id.memory_avai_cnst))
                        .setText(getString(R.string.available) + ":");
                ((TextView) findViewById(R.id.memory_avai))
                        .setText(load ? ReadSystemMemory
                                .getAvailableInternalMemorySizeText() : " 0 B");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void setSDProgress() throws Exception {
            View cntr = findViewById(R.id.sdcard);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) cntr
                    .getLayoutParams();
            lp.width = ((Double) (DensityUtil.getScreenWidth(activity) * 0.95))
                    .intValue();
            cntr.setLayoutParams(lp);

            long cntrWidth = cntr.getLayoutParams().width;
            if (blockSizeMap == null || blockSizeMap.isEmpty()) {
                blockSizeMap = FileUtil
                        .getAvailableStore(NavigationConstants.SDCARD_PATH);
            }
            Float totalSize = ((Long) blockSizeMap.get("totalSize"))
                    .floatValue();

            Float musicProgress = (MimeSrc.getCategoryRepository().get(
                    Constants.CateContants.CATE_MUSIC).categoryInfo.length / totalSize);
            Float imageProgress = MimeSrc.getCategoryRepository().get(
                    Constants.CateContants.CATE_IMAGES).categoryInfo.length
                    / totalSize;
            Float videoProgress = MimeSrc.getCategoryRepository().get(
                    Constants.CateContants.CATE_VIDEO).categoryInfo.length
                    / totalSize;
            Float docProgress = MimeSrc.getCategoryRepository().get(
                    Constants.CateContants.CATE_DOCS).categoryInfo.length
                    / totalSize;
            Float apkProgress = MimeSrc.getCategoryRepository().get(
                    Constants.CateContants.CATE_PACKAGE).categoryInfo.length
                    / totalSize;
            Float themeProgress;
            if (Config.isLewaRom) {
                themeProgress = MimeSrc.getCategoryRepository().get(
                        Constants.CateContants.CATE_THEME).categoryInfo.length
                        / totalSize;
            } else {
                themeProgress = 0f;
            }
            Float usedProgress = musicProgress + imageProgress + videoProgress
                    + docProgress + apkProgress;
            Float otherProgress = (1 - (ReadSystemMemory
                    .getAvailableExternalMemorySize() / totalSize) - usedProgress);
            if (0 == usedProgress) {
                return;
            }
            LayoutParams musicLayoutParams = findViewById(R.id.music_progress)
                    .getLayoutParams();
            musicLayoutParams.width = ((Float) (musicProgress * cntrWidth))
                    .intValue();
            LayoutParams imageLayoutParams = findViewById(R.id.picture_progress)
                    .getLayoutParams();
            imageLayoutParams.width = ((Float) (imageProgress * cntrWidth))
                    .intValue();

            LayoutParams videoLayoutParams = findViewById(R.id.video_progress)
                    .getLayoutParams();
            videoLayoutParams.width = ((Float) (videoProgress * cntrWidth))
                    .intValue();

            LayoutParams docLayoutParams = findViewById(R.id.doc_progress)
                    .getLayoutParams();
            docLayoutParams.width = ((Float) (docProgress * cntrWidth))
                    .intValue();

            LayoutParams apkLayoutParams = findViewById(R.id.apk_progress)
                    .getLayoutParams();
            apkLayoutParams.width = ((Float) (apkProgress * cntrWidth))
                    .intValue();

            LayoutParams themeLayoutParams = findViewById(R.id.theme_progress)
                    .getLayoutParams();
            themeLayoutParams.width = ((Float) (themeProgress * cntrWidth))
                    .intValue();

            LayoutParams otherLayoutParams = findViewById(R.id.other_progress)
                    .getLayoutParams();
            otherLayoutParams.width = ((Float) (otherProgress * cntrWidth))
                    .intValue();

            findViewById(R.id.music_progress)
                    .setLayoutParams(musicLayoutParams);
            findViewById(R.id.picture_progress).setLayoutParams(
                    imageLayoutParams);
            findViewById(R.id.video_progress)
                    .setLayoutParams(videoLayoutParams);
            findViewById(R.id.doc_progress).setLayoutParams(docLayoutParams);
            findViewById(R.id.apk_progress).setLayoutParams(apkLayoutParams);
            findViewById(R.id.theme_progress)
                    .setLayoutParams(themeLayoutParams);
            findViewById(R.id.other_progress)
                    .setLayoutParams(otherLayoutParams);

        }

        private void setMemProgress() throws Exception {
            View cntr = findViewById(R.id.memory);
            LayoutParams lp = cntr.getLayoutParams();
            lp.width = ((Double) (DensityUtil.getScreenWidth(activity) * 0.95))
                    .intValue();
            cntr.setLayoutParams(lp);

            long cntrWidth = cntr.getLayoutParams().width;
            Float memProgress = 1
                    - ReadSystemMemory.getAvailableInternalMemorySize()
                    .floatValue()
                    / ReadSystemMemory.getTotalInternalMemorySize()
                    .floatValue();
            LayoutParams memLayoutParams = findViewById(R.id.used)
                    .getLayoutParams();
            memLayoutParams.width = ((Float) (memProgress * cntrWidth))
                    .intValue();
            findViewById(R.id.used).setLayoutParams(memLayoutParams);
        }

        private void uiStatusUpdate() {
            if (!atTopToSearch) {
                baseSwitchSearchMain(false);
            }
            int visibility = -1;
            if (scanBarToHideFlag) {
                visibility = View.GONE;
            } else {
                visibility = View.VISIBLE;
            }
            hideScanBar(visibility);
        }

        @Override
        public void refresh() {
        }

        // install
        public void dataChanged(Object... params) {

        }

    }
}
